package controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

import model.Company;
import model.Product;
import dao.companyDAO;
import dao.productDAO;

/**
 * Servlet implementation class ListCompanyController
 */
@WebServlet(name = "ListCompanyController", urlPatterns = "/ListCompanyController")
public class ListCompanyController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ListCompanyController() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String action = request.getParameter("action");
		if (action.equals("1")) {
			companyDAO dao = new companyDAO();
			List<Company> listCompanys = dao.getAllCompany();
			JsonArray jsonArray = new JsonArray();
			JsonObject jsonObject;
			JsonObject json = new JsonObject();
			for (Company obj : listCompanys) {
				jsonObject = new JsonObject();
				jsonObject.addProperty("companyId", obj.getCompanyId());
				jsonObject.addProperty("companyName", obj.getCompanyName());
				jsonObject.addProperty("address", obj.getAddress());
				jsonObject.addProperty("contactPerson", obj.getContactPerson());
				jsonArray.add(jsonObject);
			}
			json.add("listCompany", jsonArray);
			response.getWriter().print(json);
		} else {
			String companyId = request.getParameter("companyId");
			productDAO proDao = new productDAO();
			List<Product> listProducts = proDao
					.getListProductByCompanyID(Integer.parseInt(companyId));
			JsonObject json = new JsonObject();
			JsonArray jsonArray = new JsonArray();
			JsonObject jsonObject;
			for (Product obj : listProducts) {
				jsonObject = new JsonObject();
				jsonObject.addProperty("productId", obj.getProductId());
				jsonObject.addProperty("productName", obj.getProductName());
				jsonObject.addProperty("price", obj.getPrice());
				jsonObject.addProperty("quality", obj.getQuality());
				jsonArray.add(jsonObject);
			}
			json.add("listProduct", jsonArray);
			response.getWriter().print(json);
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

	}

}
